#!/usr/bin/env node

// 高级GPIO测试脚本
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

console.log("🔬 高级GPIO测试脚本");

async function runCommand(command) {
  try {
    const result = await execAsync(command);
    return { success: true, stdout: result.stdout.trim(), stderr: result.stderr.trim() };
  } catch (error) {
    return { success: false, error: error.message, stdout: '', stderr: error.stderr || '' };
  }
}

async function testGPIOConsistency() {
  console.log("\n🔧 测试GPIO一致性...");
  
  // 1. 检查pigpio进程
  console.log("1. 检查pigpio进程:");
  const pigpioCheck = await runCommand('ps aux | grep pigpiod | grep -v grep');
  if (pigpioCheck.success && pigpioCheck.stdout) {
    console.log("   发现pigpio后台进程，这可能影响WiringPi控制:");
    console.log(`   ${pigpioCheck.stdout}`);
  } else {
    console.log("   未发现pigpio后台进程");
  }
  
  // 2. 检查引脚初始状态
  console.log("2. 检查引脚13初始状态:");
  const initialState = await runCommand('gpio -g read 13');
  console.log(`   初始状态: ${initialState.success ? initialState.stdout : '读取失败'}`);
  
  // 3. 设置引脚为输出模式
  console.log("3. 设置引脚13为输出模式:");
  const modeResult = await runCommand('gpio -g mode 13 out');
  console.log(`   设置结果: ${modeResult.success ? '成功' : '失败 - ' + modeResult.error}`);
  
  // 4. 多次写入和读取测试
  console.log("4. 多次写入和读取测试:");
  const testResults = [];
  
  for (let i = 0; i < 5; i++) {
    // 写入高电平
    const writeHigh = await runCommand('gpio -g write 13 1');
    const readAfterHigh = await runCommand('gpio -g read 13');
    
    // 等待一小段时间
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // 写入低电平
    const writeLow = await runCommand('gpio -g write 13 0');
    const readAfterLow = await runCommand('gpio -g read 13');
    
    testResults.push({
      iteration: i + 1,
      writeHighSuccess: writeHigh.success,
      readAfterHigh: readAfterHigh.success ? readAfterHigh.stdout : '读取失败',
      writeLowSuccess: writeLow.success,
      readAfterLow: readAfterLow.success ? readAfterLow.stdout : '读取失败'
    });
    
    console.log(`   第${i + 1}次测试:`);
    console.log(`     写入高电平: ${writeHigh.success ? '成功' : '失败'}`);
    console.log(`     读取结果: ${readAfterHigh.success ? readAfterHigh.stdout : '读取失败'}`);
    console.log(`     写入低电平: ${writeLow.success ? '成功' : '失败'}`);
    console.log(`     读取结果: ${readAfterLow.success ? readAfterLow.stdout : '读取失败'}`);
  }
  
  // 5. 检查引脚模式
  console.log("5. 检查引脚13当前模式:");
  const modeCheck = await runCommand('gpio -g mode 13');
  console.log(`   当前模式: ${modeCheck.success ? modeCheck.stdout : '检查失败'}`);
  
  // 6. 测试PWM模式
  console.log("6. 测试PWM模式:");
  const pwmTest = await runCommand('gpio -g mode 13 pwm && gpio -g pwm 13 512');
  console.log(`   PWM设置: ${pwmTest.success ? '成功' : '失败 - ' + (pwmTest.error || pwmTest.stderr)}`);
  
  // 7. 恢复输出模式
  console.log("7. 恢复输出模式:");
  const restoreMode = await runCommand('gpio -g mode 13 out');
  console.log(`   恢复结果: ${restoreMode.success ? '成功' : '失败'}`);
  
  return testResults;
}

async function simulateUserIssue() {
  console.log("\n🎯 模拟用户问题场景:");
  
  // 重置引脚状态
  await runCommand('gpio -g mode 13 out');
  await runCommand('gpio -g write 13 0');
  
  console.log("1. 执行: gpio -g write 13 1");
  const writeResult = await runCommand('gpio -g write 13 1');
  console.log(`   执行结果: ${writeResult.success ? '成功' : '失败'}`);
  
  console.log("2. 立即执行: gpio -g read 13");
  const readResult = await runCommand('gpio -g read 13');
  console.log(`   读取结果: ${readResult.success ? readResult.stdout : '读取失败'}`);
  
  // 等待一段时间再读取
  console.log("3. 等待100ms后再次读取:");
  await new Promise(resolve => setTimeout(resolve, 100));
  const readResult2 = await runCommand('gpio -g read 13');
  console.log(`   读取结果: ${readResult2.success ? readResult2.stdout : '读取失败'}`);
  
  return {
    writeSuccess: writeResult.success,
    immediateRead: readResult.success ? readResult.stdout : '读取失败',
    delayedRead: readResult2.success ? readResult2.stdout : '读取失败'
  };
}

async function main() {
  console.log("🚀 开始高级GPIO测试");
  
  // 运行一致性测试
  const testResults = await testGPIOConsistency();
  
  // 模拟用户问题
  const userIssueResult = await simulateUserIssue();
  
  console.log("\n📋 测试结果总结:");
  console.log(`用户问题模拟:`);
  console.log(`  写入操作: ${userIssueResult.writeSuccess ? '成功' : '失败'}`);
  console.log(`  立即读取: ${userIssueResult.immediateRead}`);
  console.log(`  延时读取: ${userIssueResult.delayedRead}`);
  
  if (userIssueResult.immediateRead === '0' && userIssueResult.delayedRead === '1') {
    console.log("  ⚠️  发现时序问题：立即读取返回0，但延时后读取返回1");
  }
  
  console.log("\n🔍 可能的问题原因:");
  console.log("1. 时序问题：写入和读取之间需要短暂稳定时间");
  console.log("2. pigpio后台进程可能干扰WiringPi控制");
  console.log("3. 引脚模式可能被其他进程重置");
  console.log("4. 硬件问题：引脚可能损坏或连接不良");
  
  console.log("\n💡 建议解决方案:");
  console.log("1. 在写入和读取之间添加短暂延时");
  console.log("2. 考虑停止pigpiod进程: sudo killall pigpiod");
  console.log("3. 检查是否有其他程序控制GPIO");
  console.log("4. 测试其他GPIO引脚确认是否为硬件问题");
}

main();